package com.xl.web.controller.zoom;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xl.base.annotation.Auth;
import com.xl.base.page.Page;
import com.xl.base.page.PageBean;
import com.xl.base.web.BaseController;
import com.xl.core.util.HtmlUtil;
import com.xl.core.util.zoom.ZoomRestAPI;
import com.xl.core.util.zoom.model.ZoomUpdate;
import com.xl.core.util.zoom.model.ZoomUser;
import com.xl.core.util.zoom.model.ZoomUserDelete;
import com.xl.web.entity.zoom.SysUser;
import com.xl.web.entity.zoom.ZoomAccount;
import com.xl.web.service.zoom.AccountService;
import com.xl.web.service.zoom.UserService;

@Controller
@RequestMapping("/accountService")
public class AccountController extends BaseController {
	protected static Logger logger = Logger.getLogger(AccountController.class);
	@Autowired(required = false)
	private AccountService<ZoomAccount> accountService;
	@Autowired(required = false)
	private UserService<SysUser> userService;

	@RequestMapping("/queryAccountByPage")
	public void queryPageAccountInfo(ZoomAccount zoomAccount, Page page)
			throws Exception {
		// 返回数据
		Map<String, Object> result = new HashMap<String, Object>();
		PageBean pageBean = accountService.queryPageAccountInfo(zoomAccount,
				page);
		result.put(this.SUCCESS, true);
		result.put(this.MSG, "查询成功!");
		result.put("data", pageBean);
		HtmlUtil.writerJson(response, result);
	}

	@RequestMapping("/queryAccount")
	@ResponseBody
	@Auth(verifyLogin = false)
	public void queryAccountInfo(ZoomAccount zoomAccount) throws Exception {
		// 返回数据
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map> accounts = accountService.queryAccountInfo(zoomAccount);
		result.put(this.SUCCESS, true);
		result.put(this.MSG, "查询成功!");
		result.put("count", accounts != null ? accounts.size() : 0);
		result.put("data", accounts);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 添加zoom账号信息
	 * 
	 * @param zoomAccount
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/saveAccount")
	@Auth(verifyLogin = false)
	public void saveAccount(ZoomAccount zoomAccount) throws Exception {
		// 校验不为空信息
		if (StringUtil.isEmpty(zoomAccount.getZoomAccount())) {
			this.sendFailureMessage(response, "zoom账号不能为空！");
			return;
		}
		if (StringUtil.isEmpty(zoomAccount.getZoomPwd())) {
			this.sendFailureMessage(response, "zoom密码不能为空！");
			return;
		}
		if (StringUtil.isEmpty(zoomAccount.getCreateUserId())) {
			this.sendFailureMessage(response, "创建人ID不能为空");
			return;
		}
		if (StringUtil.isEmpty(zoomAccount.getType() + "")
				|| ("123".indexOf(zoomAccount.getType() + "") < 0)) {
			this.sendFailureMessage(response,
					"zoom类型不能为空,且类型只能为【1基本用户；2专业用户;3公司用户。基本用户最多可以进行30分钟会议】!");
			return;
		}
		zoomAccount.setIs_temp(0);
		// 根据当前创建人ID获取归属companyid
		SysUser sysUser = this.getUserByUserId(zoomAccount.getCreateUserId());
		zoomAccount.setCompanyId(sysUser.getCompanyId());
		zoomAccount.setFirstName(sysUser.getUserName());
		// 判断用户账号是否存在
		ZoomAccount _queryparam = new ZoomAccount();
		_queryparam.setZoomAccount(zoomAccount.getZoomAccount());
		List<Map> accounts = accountService.queryAccountInfo(_queryparam);
		if (accounts != null & accounts.size() > 0) {
			this.sendFailureMessage(response,
					"zoom账号【" + zoomAccount.getZoomAccount() + "】已添加过不能重复添加!");
			return;
		}
		zoomAccount.setDept(sysUser.getCompany().getCompanyName());
		zoomAccount = accountService.saveAccount(zoomAccount);
		if (zoomAccount == null) {
			this.sendFailureMessage(response, "zoom账号添加失败!");
			return;
		}
		this.sendSuccessMessage(response, "添加账号成功！");
	}

	// 删除zoom账号
	@SuppressWarnings({ "unused", "rawtypes" })
	@ResponseBody
	@RequestMapping("/delAccount")
	@Auth(verifyLogin = false)
	public void delAccount(ZoomAccount zoomAccount) throws Exception {
		// 判断hostId和zoomAccount 不能为空
		if (StringUtil.isEmpty(zoomAccount.getId())) {
			this.sendFailureMessage(response, "删除账号失败，要删除的账号ID不能为空！");
			return;
		}

		SysUser sysUser = this.getUserByUserId(zoomAccount.getCreateUserId());
		// 根据ID查询相关信息
		List<Map> accounts = accountService.queryAccountInfo(zoomAccount);
		if (accounts != null && accounts.size() > 0) {
			Map<String, String> account = accounts.get(0);
			//ZoomRestAPI.setApiKeySecret(sysUser.getCompanyId());
			ZoomUserDelete zoomUserDel = ZoomRestAPI.deleteUser(
					account.get("hostId"), account.get("zoomAccount"));
			if (zoomUserDel.getError() != null) {
				logger.debug("删除账号失败，原因为：=="
						+ zoomUserDel.getError().getMessage());
				this.sendFailureMessage(response,
						"删除账号失败，原因为：【调用接口失败，详情请查询日志！】");
				return;
			}
			// 数据库中添加删除标志
			accountService.delAccount(zoomAccount);
			this.sendSuccessMessage(response, "删除账号成功!");
		} else {
			this.sendFailureMessage(response, "删除账号失败!");
		}

	}

	// 更新zoom账号
	@SuppressWarnings({ "unused", "rawtypes" })
	@ResponseBody
	@RequestMapping("/editAccount")
	@Auth(verifyLogin = false)
	public void editAccount(ZoomAccount zoomAccount) throws Exception {

		if (StringUtil.isEmpty(zoomAccount.getId())) {
			this.sendFailureMessage(response, "修改账号失败，ID不能为空！");
			return;
		}
		ZoomAccount temp = new ZoomAccount();
		temp.setId(zoomAccount.getId());
		// 根据ID查询相关信息
		SysUser sysUser = this.getUserByUserId(zoomAccount.getCreateUserId());
		List<Map> accounts = accountService.queryAccountInfo(temp);
		if (accounts != null && accounts.size() > 0) {
			Map<String, String> account = accounts.get(0);
		//	ZoomRestAPI.setApiKeySecret(sysUser.getCompanyId());
			ZoomUser zoomUser = new ZoomUser();
			zoomUser.setType(zoomAccount.getType());
			zoomUser.setFirst_name(zoomAccount.getFirstName());
			zoomUser.setLast_name(zoomAccount.getLastName());
			zoomUser.setMeeting_capacity(zoomAccount.getCapacity());
			zoomUser.setPmi(zoomAccount.getPmi());
			zoomUser.setId(account.get("hostId"));
			ZoomUpdate zoomUpdate = ZoomRestAPI.updateUser(zoomUser);
			if (zoomUpdate == null) {
				this.sendFailureMessage(response, "修改账号失败!");
				return;
			}

			// 调用更新接口
			accountService.editAccount(zoomAccount);
		} else {
			this.sendFailureMessage(response, "修改账号失败!");
			return;
		}
		this.sendFailureMessage(response, "修改账号成功!");

	}

	public SysUser getUserByUserId(String userId) throws Exception {
		SysUser sysuser = new SysUser(userId);
		List<SysUser> sysusers = userService.queryUserInfo(sysuser);
		sysuser = sysusers.get(0);
		String companyId = sysuser.getCompanyId();
		return sysuser;
	}

}
